<template>
	<el-dialog
		:title="dialog.title"
		v-model="dialog.dialogVisible"
		:close-on-click-modal="false"
		:close-on-press-escape="false"
		destroy-on-close
		width="1000px"
		top="0"
	>
		<el-form
			ref="form"
			:model="form"
			:rules="formRules"
			v-loading="formLoading"
			label-width="120px"
		>
			<el-tabs v-model="tabActiveName" :stretch="true" @tab-click="tabClick">
				<el-tab-pane label="基本信息" name="base">
					<el-form-item label="优惠券类型" prop="coupon_type" required>
						<el-radio-group
							v-model="form.coupon_type"
							:disabled="form.received_num > 0"
						>
							<el-radio :label="1">满X元减X元</el-radio>
							<el-radio :label="2">满X元打X折</el-radio>
							<el-radio :label="3">满X件减X元</el-radio>
							<el-radio :label="4">满X件打X折</el-radio>
						</el-radio-group>
						<div
							style="color: #f00;margin-left: 5px;"
						>
							用户领取后，不允许修改
						</div>
					</el-form-item>
					<el-row>
						<el-col :span="18">
							<el-form-item label="优惠券标题" prop="title">
								<el-input v-model="form.title" />
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="发放总量" prop="quantity_issued">
								<el-input-number
									v-model="form.quantity_issued"
									:controls="false"
									style="width: 100px"
								/>
								<div
									class="el-form-item-help"
								>
									单位：张
								</div>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="领取时间" prop="receive_time_start" required>
						<el-radio v-model="form.receive_time_type" :label="0">
							不限
						</el-radio>
						<el-radio v-model="form.receive_time_type" :label="1">
							时间区间：
							<el-date-picker
								v-model="form.receive_time_range"
								type="datetimerange"
								:shortcuts="shortcuts"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
							/>
						</el-radio>
					</el-form-item>
					<el-form-item label="用券时间" prop="time_type">
						<el-radio v-model="form.time_type" :label="1">
							时间区间：
							<el-date-picker
								v-model="form.time_range"
								type="datetimerange"
								:disabled="form.time_type === 2"
								:shortcuts="shortcuts"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
							/>
						</el-radio>
						<el-radio v-model="form.time_type" :label="2">
							领取当日起：
							<el-input-number
								v-model="form.time_days"
								:disabled="form.time_type === 1"
								placeholder="请输入内容"
								style="width: 100px"
								:controls="false"
							/>
							天可用
						</el-radio>
					</el-form-item>
					<el-form-item label="策略" prop="is_threshold">
						<el-radio v-model="form.is_threshold" :label="0">无使用门槛</el-radio>
						<el-radio v-model="form.is_threshold" :label="1">
							<template v-if="form.coupon_type === 1 || form.coupon_type === 2">
								订单满
								<el-input
									v-model="form.threshold_money"
									:disabled="form.is_threshold === 0"
									placeholder="请输入金额"
									style="width: 200px"
									v-toFixed="2"
								/>
								元
							</template>
							<template v-if="form.coupon_type === 3 || form.coupon_type === 4">
								订单满
								<el-input-number
									v-model="form.threshold_num"
									:disabled="form.is_threshold === 0"
									placeholder="请输入件数"
									style="width: 200px"
									:controls="false"
								/>
								件
							</template>
						</el-radio>
						<template v-if="form.coupon_type === 1 || form.coupon_type === 3">
							减
							<el-input
								v-model="form.discount_money"
								placeholder="请输入金额"
								style="width: 200px"
								v-toFixed="2"
							/>
							元
						</template>
						<template v-if="form.coupon_type === 2 || form.coupon_type === 4">
							打
							<el-input
								v-model="form.discount_ratio"
								placeholder="请输入折扣比例"
								style="width: 100px"
								v-toFixed="2"
							/>
							折
						</template>
					</el-form-item>
				</el-tab-pane>
				<el-tab-pane label="使用范围" name="useGoodsType">
					<div style="margin-bottom: 15px">
						<el-radio-group v-model="form.use_goods_type" @change="useGoodsTypeChange">
							<el-radio v-for="item in useGoodsTypeOptions" :key="item.value" :label="item.value">{{item.label}}</el-radio>
						</el-radio-group>
					</div>
					<div v-show="form.use_goods_type === 1 || form.use_goods_type === 2">
						<div>
							<el-tree
								:data="shopCategory"
								show-checkbox
								default-expand-all
								node-key="id"
								ref="srcIdsTree"
								highlight-current
								:props="{
									label: 'cat_name'
								}"
							/>
						</div>
					</div>
					<div v-show="form.use_goods_type === 3 || form.use_goods_type === 4">
						<div style="position: absolute; margin-left: 800px; z-index: 100">
							<el-button
								size="mini"
								style="margin-left: 15px"
								@click="openSelectDialogGoods"
							>添加</el-button
							>
						</div>
						<select-goods-table-goodsid
							ref="selectGoodsTable"
							mode="show"
							:isShowOpsBtn="true"
							@selectChange="goodsTableSelectChange"
						/>
					</div>
				</el-tab-pane>
				<el-tab-pane label="排除商品" name="excludeGoods">
					<exclude-goods-box ref="excludeGoodsBox" :baseUrl="baseUrl" v-model="excludeGoodsIds" :tableStyle="excludeGoodsBoxStyle" />
				</el-tab-pane>
				<el-tab-pane label="其他" name="other">
					<el-row>
						<el-col :span="8">
							<el-form-item label="每人限领" prop="receive_limit">
								<el-input-number v-model="form.receive_limit" :controls="false" />
								<div class="el-form-item-help">单位 张，0为不限</div>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="自动发送" prop="send_new_reg_member">
								<el-input-number
									v-model="form.send_new_reg_member"
									:controls="false"
								/>
								<div class="el-form-item-help">
									自动发送给新注册的用户 单位 张，0为不发送
								</div>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="到期提醒" prop="expire_remind">
								<el-input-number v-model="form.expire_remind" :controls="false" />
								<div class="el-form-item-help">单位 天，0为不提醒</div>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="允许分享" prop="can_share">
								<el-radio-group v-model="form.can_share">
									<el-radio :label="1">允许分享</el-radio>
									<el-radio :label="0">禁止分享</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="订单退款后策略" prop="refund_policy">
								<el-radio-group v-model="form.refund_policy">
									<el-radio :label="1">原路返回</el-radio>
									<el-radio :label="2">不退</el-radio>
								</el-radio-group>
								<div class="el-form-item-help">原路返回：只有全单退款后才触发</div>
							</el-form-item>
						</el-col>
					</el-row>
				</el-tab-pane>
			</el-tabs>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialog.dialogVisible = false">取 消</el-button>
				<el-button type="primary" v-if="!btnStatus" disabled>结束后禁止编辑</el-button>
				<el-button type="primary" v-else @click="submitData">提 交</el-button>
			</span>
		</template>
	</el-dialog>
	<select-dialog-goodsid ref="selectDialog" @select="SelectDialogGoodsCb" />
</template>

<script>
import selectDialogGoodsid from "../../shop/diyPage/selectDialogGoodsId";
import selectGoodsTableGoodsid from "../../shop/diyPage/selectGoodsTableByGoodsId";
import dayjs from "dayjs";
import excludeGoodsBox from "../components/excludeGoodsBox";
export default {
	name: "edit",
	components:{
		selectDialogGoodsid,
		selectGoodsTableGoodsid,
		excludeGoodsBox
	},
	data() {
		return {
			dialog: {
				dialogVisible: false,
				title: ""
			},
			tabActiveName: 'base',
			shopCategory: [],
			goodsSelects: [],
			excludeGoodsIds: [],
			excludeGoodsBoxStyle: {
				'width': '900px',
				'height': '500px',
			},
			baseUrl: '',
			useGoodsTypeOptions: [
				{
					label: "全场",
					value: 0
				},
				{
					label: "按分类",
					value: 1
				},
				{
					label: "指定商品",
					value: 3
				},
				/*{
					label: "按店铺",
					value: 5
				},*/
			],
			defaultForm: {
				id: 0,
				coupon_type: 1,
				title: "",
				quantity_issued: 0,
				receive_time: [],
				time_type: 1,
				time_range: [],
				time_days: 0,
				time_start: 0,
				time_end: 0,
				receive_time_type: 0,
				receive_time_range: [],
				receive_time_start: 0,
				receive_time_end: 0,
				is_threshold: 0,
				threshold_money: 0,
				threshold_num: 0,
				discount_money: 0,
				discount_ratio: 0,
				use_goods_type: 0,
				use_src_ids: [],
				receive_limit: 1,
				can_share: 1,
				send_new_reg_member: 0,
				expire_remind: 0,
				refund_policy: 2,
				status: 1,
				used_num: 0,
				received_num: 0
			},
			form: {
				id: 0,
				coupon_type: 1,
				title: "",
				quantity_issued: 0,
				receive_time: [],
				time_type: 1,
				time_range: [],
				time_days: 0,
				time_start: 0,
				time_end: 0,
				receive_time_type: 0,
				receive_time_range: [],
				receive_time_start: 0,
				receive_time_end: 0,
				is_threshold: 0,
				threshold_money: 0,
				threshold_num: 0,
				discount_money: 0,
				discount_ratio: 0,
				use_goods_type: 0,
				use_src_ids: [],
				receive_limit: 1,
				can_share: 1,
				send_new_reg_member: 0,
				expire_remind: 0,
				refund_policy: 2,
				status: 1,
				used_num: 0,
				received_num: 0
			},
			formRules: {
				title: [{ required: true, message: "必填", trigger: ["blur", "change"] }],
				quantity_issued: [
					{ required: true, message: "必填", trigger: ["blur", "change"] },
					{ type: "number", message: "请输入正确格式", trigger: ["blur", "change"] }
				],
				time_type: [{ required: true, message: "必填", trigger: ["blur", "change"] }],
				is_threshold: [{ required: true, message: "必填", trigger: ["blur", "change"] }]
			},
			shortcuts: [
				{
					text: "一个月",
					value: (() => {
						const end = new Date();
						const start = new Date();
						end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
						return [start, end];
					})()
				},
				{
					text: "三个月",
					value: (() => {
						const end = new Date();
						const start = new Date();
						end.setTime(start.getTime() + 3600 * 1000 * 24 * 91);
						return [start, end];
					})()
				},
				{
					text: "半年",
					value: (() => {
						const end = new Date();
						const start = new Date();
						end.setTime(start.getTime() + 3600 * 1000 * 24 * 183);
						return [start, end];
					})()
				},
				{
					text: "一年",
					value: (() => {
						const end = new Date();
						const start = new Date();
						end.setTime(start.getTime() + 3600 * 1000 * 24 * 365);
						return [start, end];
					})()
				},
				{
					text: "十年",
					value: (() => {
						const end = new Date();
						const start = new Date();
						end.setTime(start.getTime() + 3600 * 1000 * 24 * 3650);
						return [start, end];
					})()
				}
			],
			btnStatus: true,
			excludeTableProps: {
				label: 'goods_name',
				value: 'id',
				keyword: "keyword"
			},
			formLoading: false
		}
	},
	created() {
		this.getBaseUrl();
	},
	methods: {
		SelectDialogGoodsCb(selects) {
			selects.map((e) => {
				if (!this.goodsSelects.includes(e)) {
					this.goodsSelects.push(e);
				}
			});
			if (this.$refs['selectGoodsTable']) {
				this.$refs['selectGoodsTable'].initData("show", this.baseUrl, this.goodsSelects);
			}
		},
		async getBaseUrl() {
			this.baseUrl = await this.$TOOL.getBaseUrl(this.$API)
		},
		goodsTableSelectChange(s) {
			this.goodsSelects = s;
		},
		setFormData(that,formData) {
			if (formData.discount_ratio > 0) {
				formData.discount_ratio = formData.discount_ratio / 1000;
			}
			if (formData.discount_money > 0) {
				formData.discount_money = formData.discount_money / 100;
			}
			if (formData.is_threshold === 1) {
				if (formData.threshold_money > 0) {
					formData.threshold_money = formData.threshold_money / 100;
				}
			}
			if (formData.use_goods_type > 0 && formData.use_src_ids && formData.use_src_ids.length > 0) {
				switch (formData.use_goods_type) {
					case 1:
					case 2:
						if (this.shopCategory.length < 1) {
							that.getShopCategory(function () {
								that.refs.srcIdsTree.setCheckedKeys(formData.use_src_ids);
							});
						} else {
							that.refs.srcIdsTree.setCheckedKeys(formData.use_src_ids);
						}
						break;
					case 3:
					case 4:
						this.goodsTableSelectChange(formData.use_src_ids.concat());
						if (this.$refs['selectGoodsTable']) {
							this.$refs['selectGoodsTable'].initData("show", this.baseUrl, formData.use_src_ids);
						}
						break;
				}
			}

			if (formData.time_type == 1) {
				formData.time_range = [formData.time_start, formData.time_end];
			} else {
				formData.time_range = [];
			}
			if (formData.receive_time_type === 1) {
				formData.receive_time_range = [formData.receive_time_start, formData.receive_time_end];
			} else {
				formData.receive_time_range = [];
			}

			that.form = formData;

			that.$refs.excludeGoodsBox.setExcludeGoodsIds(formData.exclude_goods_ids);

			that.formLoading = false;
		},
		getOneData(_id) {
			const that = this;
			this.formLoading = true;
			this.$API.shop.coupon.info({ id: _id }).then((res) => {
				if (res.code === 0) {
					that.setFormData(that, res.data);
				} else {
					that.$message.error(res.message);
				}
			});
		},
		open() {
			this.dialog.title = "新增优惠券";
			// 初始化数据
			this.form = Object.assign({}, this.defaultForm);
			this.dialog.dialogVisible = true;
		},
		edit(_id, btnStatus = true) {
			this.dialog.title = "编辑优惠券";
			this.btnStatus = btnStatus;
			this.form = Object.assign({}, this.defaultForm);
			this.dialog.dialogVisible = true;
			this.getOneData(_id);
		},
		closePop() {
			this.dialog.dialogVisible = false;
		},
		getShopCategory(_fn) {
			this.$API.shop.category.list({ type_str: "shop" }).then((res) => {
				if (res.code === 0) {
					this.shopCategory = this.$TOOL.deepTree(res.data, "parent_id");
					if (typeof _fn === "function") {
						_fn();
					}
				}
				else {
					this.$message.error(res.message);
				}
			});
		},
		tabClick(e) {
			if (e.paneName === "useGoodsType") {
				switch (this.form.use_goods_type) {
					case 1:
					case 2:
						if (this.shopCategory.length < 1) {
							this.getShopCategory(false);
						}
						break;
				}
			}
		},
		useGoodsTypeChange(e) {
			switch (e) {
				case 1:
				case 2:
					if (this.shopCategory.length < 1) {
						this.getShopCategory(false);
					}
					break;
			}
		},
		openSelectDialogGoods() {
			this.$refs.selectDialog.create();
		},
		submitData() {
			this.$refs.form.validate((valid) => {
				if (!valid) {
					return false;
				}
				let methodName = "add";
				if (this.form.id > 0) {
					methodName = "update";
				}

				let formData = Object.assign({}, this.form);

				if (formData.threshold_money > 0) {
					formData.threshold_money = formData.threshold_money * 100;
				}
				if (formData.discount_ratio > 0) {
					formData.discount_ratio = formData.discount_ratio * 1000;
				}
				if (formData.discount_money > 0) {
					formData.discount_money = formData.discount_money * 100;
				}
				if (formData.is_threshold === 0) {
					formData.threshold_money = 0;
					formData.threshold_num = 0;
				}

				if (formData.use_goods_type > 0) {
					switch (formData.use_goods_type) {
						case 1:
						case 2:
							formData.use_src_ids = this.refs.srcIdsTree.getCheckedKeys();
							break;
						case 3:
						case 4:
							formData.use_src_ids = this.goodsSelects;
							break;
					}
				} else {
					formData.use_src_ids = [];
				}

				if (formData.time_type === 1) {
					if (
						formData.time_range.length < 0 ||
						!formData.time_range[0] ||
						!formData.time_range[1]
					) {
						this.$message.warning("请选择时间区间");
						return;
					}
					formData.time_start = dayjs(formData.time_range[0]).format(
						"YYYY-MM-DD HH:mm:ss"
					);
					formData.time_end = dayjs(formData.time_range[1]).format("YYYY-MM-DD HH:mm:ss");
				} else {
					formData.time_start = "";
					formData.time_end = "";
				}
				if (formData.receive_time_type === 1) {
					if (
						formData.receive_time_range.length < 0 ||
						!formData.receive_time_range[0] ||
						!formData.receive_time_range[1]
					) {
						this.$message.warning("请选择领取时间区间");
						return;
					}
					formData.receive_time_start = dayjs(formData.receive_time_range[0]).format(
						"YYYY-MM-DD HH:mm:ss"
					);
					formData.receive_time_end = dayjs(formData.receive_time_range[1]).format("YYYY-MM-DD HH:mm:ss");
				} else {
					formData.receive_time_start = "";
					formData.receive_time_end = "";
				}

				delete formData.time_range;
				delete formData.received_num;
				delete formData.receive_time_range;
				delete formData.used_num;

				if (formData.remark === null) {
					formData.remark = "";
				}
				formData.exclude_goods_ids = this.excludeGoodsIds.map(e => e.id);
				if (!formData.exclude_goods_ids) {
					formData.exclude_goods_ids = [];
				}
				this.formLoading = true;
				this.$API.shop.coupon[methodName](formData)
					.then((res) => {
						console.log(res);
						this.formLoading = false;
						if (res.code === 0) {
							this.$message.success(this.dialog.title + "成功");
							this.closePop();
							this.$emit("success", formData);
						}
						else {
							this.$message.error(res.message);
						}
					})
					.catch((err) => {
						this.formLoading = false;
						this.$message.error(err);
					});

				console.log(this.form);
			});
		}
	}
}
</script>

<style scoped>
.el-form-item-help{
	color: #cbcdd0;
	font-size: 12px;
}
</style>
